import React, { Component } from "react";
import { Layout, message, Spin } from "antd";
import "./dashboard.scss";
import DashboardSide from "./DashboardSide";
import DashboardHeader from "./DashboardHeader";
import DashboardContent from "./DashboardContent";
import DashboardFooter from "./DashboardFooter";
import * as _ from "lodash";
import dashboardService from "./DashboardService";
import { observer } from "mobx-react";
import { observable, computed, action, runInAction } from "mobx";

@observer
class DashboardPage extends Component {
  @observable collapsed = false;
  @observable menuList = [];
  @observable tabs: any[] = [];
  @observable activeTab = "";
  @observable startRender = false;

  @computed get menuFoldType() {
    return this.collapsed ? "menu-unfold" : "menu-fold";
  }

  componentDidMount() {
    dashboardService.menuList().then((res: any) => {
      if (res.status === 0) {
        runInAction(() => {
          this.startRender = true;
          this.menuList = res.data;
        });
      } else {
        message.error(res.msg);
      }
    });
  }

  @action
  onClickMenuFold = () => {
    console.log("menuFold");
    this.collapsed = !this.collapsed;
  };

  @action
  updateTabs = (item: any) => {
    const index = _.findIndex(this.tabs, (o: any) => o.id === item.id);
    if (index === -1) {
      this.tabs.push(item);
    }
    this.activeTab = item.id;
  };

  @action
  onTabClick = (key: string) => {
    console.log("tab click ", key);
    this.activeTab = key;
  };

  @action
  closeTab = (key: string) => {
    let index = this.tabs.findIndex((item: any) => item.id === key);
    if (index > 0) {
      index--;
    }
    this.tabs = this.tabs.filter((item: any) => item.id !== key);
    const preTab = this.tabs.find((ele, ind) => ind === index);
    this.activeTab = preTab ? preTab.id : "";
  };

  render() {
    // console.log("unmount is ", this.startRender);
    return this.startRender ? (
      <Layout className="dashboard-page">
        <Layout.Content className="layout-content">
          <Layout className="sub-content">
            <DashboardSide
              collapsed={this.collapsed}
              updateTabs={this.updateTabs}
              menuList={this.menuList}
            />
            <Layout>
              <DashboardHeader
                onClickMenuFold={this.onClickMenuFold}
                menuFoldType={this.menuFoldType}
              />
              <DashboardContent
                activeTab={this.activeTab}
                tabs={this.tabs}
                onTabClick={this.onTabClick}
                closeTab={this.closeTab}
              />
            </Layout>
          </Layout>
        </Layout.Content>
        <DashboardFooter />
      </Layout>
    ) : (<div className="page-loading"><Spin size="large" tip="加载中..." /></div>);
  }
}

export default DashboardPage;
